package com.warthur.vertx.demo.handler;

import com.warthur.vertx.demo.common.enums.ErrorCode;
import com.warthur.vertx.demo.common.enums.HttpStatus;
import com.warthur.vertx.demo.common.utils.ResponseUtils;
import com.warthur.vertx.demo.excepton.SystemException;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.PubSecKeyOptions;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.ext.jwt.JWTOptions;
import io.vertx.ext.web.RoutingContext;
import org.apache.commons.lang3.StringUtils;

/**
 * @author warthur
 * @date 2019/10/11
 */
public class SecurityHandler {

    private static JWTAuthOptions config = new JWTAuthOptions()
            .addPubSecKey(new PubSecKeyOptions()
                    .setAlgorithm("HS256")
                    .setPublicKey("2222222222")
                    .setSecretKey("23ed6667f5a2fb9e1829f874e91d8733")
                    .setSymmetric(true));

    public static void token(RoutingContext context) {

        JWTAuth provider = JWTAuth.create(context.vertx(), config);

        JsonObject jsonObject = new JsonObject().put("username", "developer")
                .put("open_id", "23ed6667f5a2fb9e1829f874e91d8733");
        JWTOptions jwtOptions = new JWTOptions().setExpiresInSeconds(3600);

        String token = provider.generateToken(jsonObject, jwtOptions);

        ResponseUtils.build(context).success().body(token);
    }

    public static void authorize(RoutingContext context) {

        JWTAuth provider = JWTAuth.create(context.vertx(), config);

        HttpServerRequest request = context.request();

        String token = request.getHeader("Authorization");

        if (StringUtils.isEmpty(token)) {
            // 403
            context.fail(HttpStatus.FORBIDDEN.value(), new SystemException(ErrorCode.AUTH_TOKEN_ERROR));
        } else {
            provider.authenticate(new JsonObject().put("jwt", token), auth -> {
                if (auth.succeeded()) {
                    context.next();
                }

                if (auth.failed()) {
                    ResponseUtils.build(context).message(auth.cause().getMessage()).body(token);
                }
            });
        }

    }
}
